package org.will.demo.events;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.will.common.http.HttpClientUtil;
import org.will.common.http.Response;
import org.will.common.metric.TestCounter;
import org.will.demo.events.dto.*;
import org.will.demo.view.MQDemoView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by EdifierWill on 2016/9/1.
 */
public class RestApiClient {

    public void create(MQDemoView view){
        HttpClientUtil clientUtil = new HttpClientUtil();
        ObjectMapper mapper = new ObjectMapper();

        String url = "http://localhost:8080/index/add";
//        String url = "http://puppet2.chinacloudapp.cn:8090/second-search/index/add";
        try {
            List<String> sortFields = new ArrayList<String>();
            sortFields.add("price");
            sortFields.add("inventory");

            AddRequest addRequest = new AddRequest();
            addRequest.setId(view._id.toString());
            addRequest.setSearch_index(view._ename);
            Map<String, String> content = new HashMap<String, String>();
            content.put("price", view._price.toString());
            content.put("inventory", view._inventory.toString());
            addRequest.setContent(content);
            addRequest.setSort_fields(sortFields);

            String jsonStr = mapper.writeValueAsString(addRequest);
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type","application/json; charset=UTF-8");
            Response re = clientUtil.post(url, jsonStr.getBytes("UTF-8"), headers);
            String responseContent = new String(re.getContent(),"UTF-8");
            //System.out.println(responseContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void update(MQDemoView view){
        HttpClientUtil clientUtil = new HttpClientUtil();
        ObjectMapper mapper = new ObjectMapper();

        String url = "http://localhost:8080/index/update/items";
        try {
            UpdateItemsRequest updateItemsRequest = new UpdateItemsRequest();
            updateItemsRequest.setId(view._id.toString());
            Map<String, String> content = new HashMap<String, String>();
            content.put("price",view._price.toString());
            content.put("inventory", view._inventory.toString());
            updateItemsRequest.setContent(content);

            String jsonStr = mapper.writeValueAsString(updateItemsRequest);
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type","application/json; charset=UTF-8");
            Response re = clientUtil.put(url, jsonStr.getBytes("UTF-8"), headers);
            String responseContent = new String(re.getContent(),"UTF-8");
            //System.out.println(responseContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
